<template>
  <div class="container">
    <div class="title mb-4">规范文件标签维护</div>

    <!-- 查询表单 -->
    <div class="border-bottom">
      <el-form
        :model="formModel"
        ref="queryForm"
        label-width="100px"
        label-position="right"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="规范名称" prop="chineseName">
              <xcmg-input
                v-model="formModel.chineseName"
                placeholder="请输入规范名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item>
              <xcmg-button stoke @click="handleSearch">查询</xcmg-button>
              <xcmg-button @click="resetForm" class="ml-2">重置</xcmg-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="button-group">
      <xcmg-button type="primary" @click="handleAdd">
        <svg-icon name="Regular" />
        <div class="spacer"></div>
        新建
      </xcmg-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <xcmg-table
        :data="tableData"
        v-loading="loading"
        height="100%"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column
          prop="uid"
          label="编号"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          prop="chineseName"
          label="规范名称"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column prop="version" label="记录版本" width="160" />
        <el-table-column
          prop="category"
          label="规范应用分类标签"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          prop="level"
          label="标准级别"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          prop="applicableModels"
          label="适用机型"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          fixed="right"
          label="启用"
          min-width="100"
          align="center"
        >
          <template #default="{ row }">
            <xcmg-switch
              size="large"
              inline-prompt
              active-text="是"
              inactive-text="否"
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="140">
          <template #default="{ row }">
            <xcmg-button type="text" size="small" @click="editRow(row)">
              历史版本
            </xcmg-button>
            <xcmg-button type="text" size="small" @click="editRow(row)">
              编辑
            </xcmg-button>
          </template>
        </el-table-column>
      </xcmg-table>

      <!-- 分页 -->
      <div class="fixed-pagination">
        <xcmg-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 50, 100, 200, 500]"
          :total="total"
          background
          layout="total,sizes,prev, pager, next,jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
  <newBuilt v-model:visible="newVisible" :title="title" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance } from "element-plus";
import { XcmgMessageBox, XcmgMessage } from "xcmg-components";
import { useToggle } from "@/hooks/useToggle";
import { SvgIcon } from "xcmg-components";
import newBuilt from "./components/newBuilt.vue";

// ✅ 修正后的数据结构：添加 version, category, level, applicableModels
interface TableItem {
  id: number;
  uid: string;
  chineseName: string;
  version: string; // 新增：记录版本
  category: string; // 新增：规范应用分类标签
  level: string; // 新增：标准级别
  applicableModels: string; // 新增：适用机型
}

const mockTableData: TableItem[] = [
  {
    id: 1,
    uid: "STD-001",
    chineseName: "物料编码规范",
    version: "V1.0",
    category: "编码管理",
    level: "企业标准",
    applicableModels: "所有机型",
  },
  {
    id: 2,
    uid: "STD-002",
    chineseName: "物料名称命名规则",
    version: "V2.0",
    category: "命名规范",
    level: "行业标准",
    applicableModels: "A系列,B系列",
  },
  {
    id: 3,
    uid: "STD-003",
    chineseName: "单位重量规范",
    version: "V1.5",
    category: "参数标准",
    level: "企业标准",
    applicableModels: "全部",
  },
  {
    id: 4,
    uid: "STD-004",
    chineseName: "颜色分类标准",
    version: "V3.0",
    category: "分类标签",
    level: "内部标准",
    applicableModels: "C系列,D系列",
  },
  {
    id: 5,
    uid: "STD-005",
    chineseName: "环保材料规范",
    version: "V2.1",
    category: "环保标准",
    level: "国家标准",
    applicableModels: "E系列",
  },
];

// 表单引用
const queryForm = ref<FormInstance>();

// 查询表单数据
const formModel = reactive({
  chineseName: "", // 规范名称
});

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 表格数据
const tableData = ref<TableItem[]>([]);
const loading = ref(false);
const selectedRows = ref<TableItem[]>([]);
const title = ref<string>("");
const [newVisible, newBuiltVisible] = useToggle();

// 获取表格数据（使用 mock 数据）
const fetchTableData = async () => {
  try {
    loading.value = true;
    await new Promise((resolve) => setTimeout(resolve, 300));

    let filteredData = mockTableData;

    // 按版本筛选（可选）
    if (formModel.chineseName) {
      filteredData = filteredData.filter(
        (item) => item.chineseName === formModel.chineseName
      );
    }

    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;

    tableData.value = filteredData.slice(start, end);
    total.value = filteredData.length;
  } catch (error) {
    console.error("获取数据失败:", error);
    XcmgMessage({ message: "数据加载失败", type: "error" });
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 查询 & 重置
const handleSearch = () => {
  currentPage.value = 1;
  fetchTableData();
};

const resetForm = () => {
  if (queryForm.value) {
    queryForm.value.resetFields();
  }
  handleSearch();
};

// 分页事件
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  fetchTableData();
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  fetchTableData();
};

// 行选择
const handleSelectionChange = (rows: TableItem[]) => {
  selectedRows.value = rows;
};

// 新建
const handleAdd = () => {
  title.value = "新建";
  newBuiltVisible();
};

// 编辑
const editRow = (row: TableItem) => {
  title.value = "编辑";
  newBuiltVisible();
};

// 初始化
onMounted(() => {
  fetchTableData();
});
</script>

<style scoped>
.container {
  padding: 20px;
  height: calc(100vh - 64px - 56px - 40px);
  display: flex;
  flex-direction: column;
}

.title {
  font-weight: bold;
  font-size: 20px;
}

.mb-4 {
  margin-bottom: 16px;
}

.border-bottom {
  border-bottom: 1px solid #e5e7eb;
}

.button-group {
  padding: 16px 0;
  display: flex;
  gap: 12px;
}

.spacer {
  width: 8px;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.fixed-pagination {
  position: sticky;
  bottom: 0;
  background: #fff;
  padding-top: 20px;
  display: flex;
  justify-content: flex-end;
  z-index: 1;
}

:deep(.el-form-item__content) {
  justify-content: flex-end;
}
</style>
